<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\Request;
use sheep\facade\Captcha;
use sheep\traits\ClearCache;
use sheep\model\Config;
use sheep\controller\Backend;
use sheep\exception\SheepException;
use sheep\model\ThirdOauth;
use app\admin\model\auth\Role as RoleModel;
use app\admin\model\auth\AdminLog as AdminLogModel;
use app\seller\model\Store as StoreModel;
use app\admin\model\auth\Admin as AdminModel;

class Index extends Backend
{

    use ClearCache;

    /**
     * 后台初始化
     *
     * @return void
     */
    public function init()
    {
        // 基础配置
        $basicSite = Config::getConfigs('basic.site');
        $data = [
            'name' => $basicSite['name'],
            'logo' => $basicSite['logo'],
            'domainurl' => domainurl('', true),
            'filesystem' => config('filesystem.default'),
            'version' => $basicSite['version'],
            'sheep_version' => \sheep\service\SheepService::version(),
            'is_pro' => check_env('commission', false)
        ];
        return success('获取成功', $data);
    }

    /**
     * 获取登录验证码|极验验证码配置
     *
     * @return void
     */
    public function captcha()
    {
        $response = Captcha::captcha();

        return $response;
    }

    /**
     * 登录配置
     *
     * @return void
     */
    public function loginConfig()
    {
        $login_bg = Config::getConfigField('basic.login.bg');
        $captcha_mode = config('captcha.captcha');
        
        $data = [
            "background" => $login_bg, // 登录背景图
            "mode" => $captcha_mode, // code 噪点验证码图片 || geetest 极验验证码 || none 无需验证
        ];
        
        $config = [];
        if ($captcha_mode == 'geetest') {
            try {
                $data['config'] = Captcha::captcha();
            } catch (\Exception $e) {
                return error('极验验证码配置错误', $data);
            }
        } else if ($captcha_mode == 'code') {
            $data['config'] = ['url' => request()->domain() . '/admin/index/captcha'];
        }

        return success('获取成功', $data);
    }

    /**
     * 管理员登录
     *
     * @return \think\Response
     */
    public function login(Request $request)
    {
        if ($this->auth()->user()) {
            throw new SheepException('您已登录,不需要重新登录');
        }

        $this->svalidate($request->param(), '.' . 'login_' . config('captcha.captcha'));   // 验证参数
        $account = $request->only(['account', 'password']);

        if ($this->auth()->attempt($account)) {
            $admin = $this->auth()->user();
            return success('登录成功');
        }

        return success('登录失败');
    }


    /**
     * 权限列表
     *
     * @return void
     */
    public function rules()
    {
        $rules = $this->auth()->getAccess(false);

        return success('获取成功', $rules);
    }


    /**
     * 获取管理员个人资料
     *
     * @return void
     */
    public function profile()
    {
        $admin = $this->auth()->user();
        $admin->role = RoleModel::find($admin->role_id);
        $admin->oauth_info = ThirdOauth::where('admin_id', $admin->id)->field('openid')->find();
        return success('个人信息', $admin);
    }


    /**
     * 当前管理员日志
     *
     * @return void
     */
    public function adminLog()
    {
        $admin = $this->auth()->user();

        $adminLogs = AdminLogModel::sheepFilter()->where('admin_id', $admin->id)->with('admin')->paginate(request()->param('list_rows', 10));

        return success('获取成功', $adminLogs);
    }


    /**
     * 更新个人资料
     *
     * @return void
     */
    public function update(Request $request)
    {
        $admin = $this->auth()->user();

        $params = $request->param();
        // todo: 手机号邮箱验证
        $admin->nickname = $params['nickname'];
        $admin->mobile = $params['mobile'];
        $admin->avatar = $params['avatar'];
        $admin->email = $params['email'];

        if(!empty($params['password'])) {
            $salt = mt_rand(1000, 9999);
            $admin->salt = $salt;
            $admin->password = $admin->encryptPassword($params['password'], $salt);
        }

        $admin->save();

        return success('更新成功', $admin);
    }



    public function getAdminInfo(){

        $adminId = $this->auth()->user()->id;

        $admin = AdminModel::where('id',$adminId)->find();

        $admin->role = RoleModel::find($admin->role_id);
        $admin->oauth_info = ThirdOauth::where('admin_id', $admin->id)->field('openid')->find();

        if(!empty($admin->organ_id)){
            $data = StoreModel::where('organ_id',$admin->organ_id)->field('type')->select()->toArray();
            $data = array_column($data, 'type');
            $category_text = [];
            foreach($data as $key=>$val){
                if($val==1){
                    $category_text[] = '电商商家';
                }elseif ($val==2){
                    $category_text[] = '团购商家';
                }elseif ($val==3){
                    $category_text[] = '外卖商家';
                }
            }
            $admin->category_text =  implode(',', $category_text);
        }else{
            $admin->category_text = null;
        }
        return success('个人信息', $admin);
    }



    /**
     * 更新商家信息
     *
     * @return void
     */
    public function shopUpdate(Request $request)
    {
        $admin = $this->auth()->user();

        $params = $request->param();
        // todo: 手机号邮箱验证

        $admin->account = $params['account']??'';
        $admin->mobile = $params['mobile'];
        $admin->email = $params['email'];
        $admin->legal_person_name = $params['legal_person_name']??'';
        $admin->legal_person_bank_account = $params['legal_person_bank_account']??'';
        $admin->legal_person_id_card = $params['legal_person_id_card']??'';
        $admin->legal_person_phone = $params['legal_person_phone']??'';
        $admin->platform_pay_password = $params['platform_pay_password']??'';

        if(!empty($params['password'])) {
            $salt = mt_rand(1000, 9999);
            $admin->salt = $salt;
            $admin->password = $admin->encryptPassword($params['password'], $salt);
        }

        $admin->save();

        return success('更新成功', $admin);
    }



    /**
     * 清除缓存
     *
     * @param Request $request
     * @return void
     */
    public function clearCache(Request $request)
    {
        $this->clearAll();

        return success('清理成功');
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return void
     */
    public function logout(Request $request)
    {
        $this->auth()->logout();

        return success('注销成功');
    }

}
